package com.dog.basics.service.mtkj.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dog.basics.bean.dto.admin.mtkj.GoodsEvaluateFromDto;
import com.dog.basics.bean.dto.api.mtkj.ApiGoodsEvaluateAddDto;
import com.dog.basics.bean.dto.api.mtkj.ApiGoodsEvaluateEditDto;
import com.dog.basics.bean.dto.api.mtkj.ApiGoodsEvaluateFromDto;
import com.dog.basics.bean.model.common.DogUser;
import com.dog.basics.bean.model.mtkj.*;
import com.dog.basics.bean.vo.admin.mtkj.GoodsEvaluateVo;
import com.dog.basics.bean.vo.api.mtkj.ApiGoodsEvaluateVo;
import com.dog.basics.common.util.Json;
import com.dog.basics.common.util.PageParam;
import com.dog.basics.dao.common.DogUserMapper;
import com.dog.basics.dao.mtkj.*;
import com.dog.basics.security.util.SecurityUtils;
import com.dog.basics.service.mtkj.IMtGoodsEvaluateService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品评价表 服务实现类
 * </p>
 *
 * @author wph
 * @since 2020-11-09
 */
@Service
@AllArgsConstructor
public class MtGoodsEvaluateServiceImpl extends ServiceImpl<MtGoodsEvaluateMapper, MtGoodsEvaluate> implements IMtGoodsEvaluateService {
    private final MtOrderGoodsMapper mtOrderGoodsMapper;
    private final MtOrderMapper mtOrderMapper;
    private final MtGoodsMapper mtGoodsMapper;
    private final DogUserMapper dogUserMapper;
    private final MtShoppingMapper mtShoppingMapper;

    /**
     * 分页的条件公用类
     *
     * @param name,mobile
     * @param goodIds
     */
    public List<Long> getgoodIdsWhere(String name, List<Long> goodIds) {
        List<Long> collect = mtGoodsMapper.selectList(Wrappers.<MtGoods>lambdaQuery().like(StrUtil.isNotBlank(name), MtGoods::getName, name)).stream().map(e -> e.getId()).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect)) {
            goodIds = collect;
        } else {
            goodIds.add(-2L);
        }
        return goodIds;
    }

    /**
     * 分页的条件公用类
     *
     * @param name,mobile
     * @param userIds
     */
    public List<Long> getuserIdsWhere(String name, String mobile, List<Long> userIds) {
        List<Long> collect = dogUserMapper.selectList(Wrappers.<DogUser>lambdaQuery().like(StrUtil.isNotBlank(mobile), DogUser::getUserMobile, mobile).like(StrUtil.isNotBlank(name), DogUser::getNickName, name)).stream().map(e -> e.getUserId()).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect)) {
            userIds = collect;
        } else {
            userIds.add(-2L);
        }
        return userIds;
    }

    /**
     * @Description: 分页商品评价列表 pc
     * @Param: status
     * @return: IPage<PlatePageVo>
     * @Author: wph
     * @Date:
     */
    @Override
    public IPage<GoodsEvaluateVo> getPageList(PageParam page, GoodsEvaluateFromDto obj) {
        // 判断所属商品ID
        List<Long> goodIds = CollUtil.newArrayList();
        if (StrUtil.isNotBlank(obj.getUserName())) {
            goodIds = getgoodIdsWhere(obj.getUserName(), goodIds);
        }
        // 判断所属用户ID
        List<Long> userIds = CollUtil.newArrayList();
        if (StrUtil.isNotBlank(obj.getUserName()) || StrUtil.isNotBlank(obj.getUserMobile())) {
            userIds = getuserIdsWhere(obj.getUserName(), obj.getUserMobile(), userIds);
        }
        IPage iPage = this.page(page, Wrappers.<MtGoodsEvaluate>lambdaQuery()
                .in(CollUtil.isNotEmpty(goodIds), MtGoodsEvaluate::getGoodsId, goodIds)
                .in(CollUtil.isNotEmpty(userIds), MtGoodsEvaluate::getUserId, userIds)
                .like(StrUtil.isNotBlank(obj.getContent()), MtGoodsEvaluate::getContent, obj.getContent())
                .eq(ObjectUtil.isNotNull(obj.getUserId()), MtGoodsEvaluate::getUserId, obj.getUserId())
                .eq(ObjectUtil.isNotNull(obj.getOrderId()), MtGoodsEvaluate::getOrderId, obj.getOrderId())
                .eq(ObjectUtil.isNotNull(obj.getGoodsId()), MtGoodsEvaluate::getGoodsId, obj.getGoodsId())
                .eq(ObjectUtil.isNotNull(obj.getOrderGoodsId()), MtGoodsEvaluate::getOrderGoodsId, obj.getOrderGoodsId())
                .eq(ObjectUtil.isNotNull(obj.getIsAnonymous()), MtGoodsEvaluate::getIsAnonymous, obj.getIsAnonymous())
                .between(ObjectUtil.isNotNull(obj.getStartTime()) && ObjectUtil.isNotNull(obj.getEndTime()), MtGoodsEvaluate::getCreateTime, obj.getStartTime(), obj.getEndTime())
                .orderByDesc(MtGoodsEvaluate::getCreateTime));
        List<MtGoodsEvaluate> records = iPage.getRecords();
        iPage.setRecords(records.stream().map(e -> {
            GoodsEvaluateVo newsVo = new GoodsEvaluateVo();
            BeanUtil.copyProperties(e, newsVo);
            //查询
            MtGoods mtGoods = mtGoodsMapper.selectById(e.getGoodsId());
            DogUser dogUser = dogUserMapper.selectById(e.getUserId());
            newsVo.setUserName(ObjectUtil.isNotNull(dogUser) ? dogUser.getNickName() : "");
            newsVo.setUserMobile(ObjectUtil.isNotNull(dogUser) ? dogUser.getUserMobile() : "");
            newsVo.setGoodsName(ObjectUtil.isNotNull(mtGoods) ? mtGoods.getName() : "");
            if (StrUtil.isNotBlank(e.getImage()) && !e.getImage().equals("-1")) {
                List<String> ts = null;
                try {
                    //ts = JSONUtil.toBean(e.getFeedbackImgArray(), ArrayList.class);
                    ts = Json.parseArray(e.getImage(), String[].class);
                } catch (Exception ex) {
                    ts = CollUtil.newArrayList();
                }
                newsVo.setImage(ts);
            }
            return newsVo;
        }).collect(Collectors.toList()));
        return iPage;

    }

    /**
     * @Description: 分页我的商品评价列表
     * @Param: status
     * @return: IPage<PlatePageVo>
     * @Author: wph
     * @Date:
     */
    @Override
    public IPage<ApiGoodsEvaluateVo> getApiPageList(PageParam page, ApiGoodsEvaluateFromDto obj) {
        IPage iPage = this.page(page, Wrappers.<MtGoodsEvaluate>lambdaQuery()
                .eq(ObjectUtil.isNotNull(obj.getUserId()), MtGoodsEvaluate::getUserId, obj.getUserId())
                .eq(ObjectUtil.isNotNull(obj.getOrderId()), MtGoodsEvaluate::getOrderId, obj.getOrderId())
                .eq(ObjectUtil.isNotNull(obj.getGoodsId()), MtGoodsEvaluate::getGoodsId, obj.getGoodsId())
                .eq(ObjectUtil.isNotNull(obj.getOrderGoodsId()), MtGoodsEvaluate::getOrderGoodsId, obj.getOrderGoodsId())
                .orderByDesc(MtGoodsEvaluate::getCreateTime));
        List<MtGoodsEvaluate> records = iPage.getRecords();
        iPage.setRecords(records.stream().map(e -> {
            ApiGoodsEvaluateVo newsVo = new ApiGoodsEvaluateVo();
            BeanUtil.copyProperties(e, newsVo);
            //查询
            MtGoods mtGoods = mtGoodsMapper.selectById(e.getGoodsId());
            DogUser dogUser = dogUserMapper.selectById(e.getUserId());
            newsVo.setUserName(ObjectUtil.isNotNull(dogUser) ? dogUser.getNickName() : "");
            newsVo.setGoodsName(ObjectUtil.isNotNull(mtGoods) ? mtGoods.getName() : "");
            newsVo.setPicture(ObjectUtil.isNotNull(mtGoods) ? mtGoods.getPicture() : "");
            newsVo.setPic(ObjectUtil.isNotNull(dogUser) ? dogUser.getPic() : "");
            if (StrUtil.isNotBlank(e.getImage()) && !e.getImage().equals("-1")) {
                List<String> ts = null;
                try {
                    //ts = JSONUtil.toBean(e.getFeedbackImgArray(), ArrayList.class);
                    ts = Json.parseArray(e.getImage(), String[].class);
                } catch (Exception ex) {
                    ts = CollUtil.newArrayList();
                }
                newsVo.setImage(ts);
            }
            return newsVo;
        }).collect(Collectors.toList()));
        return iPage;

    }

    /**
     * @Description: 增加我的商品评价
     * @Param: ApiGoodsEvaluateAddDto
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/29  0027
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveObj(ApiGoodsEvaluateAddDto obj) {
        MtOrder mtOrder = mtOrderMapper.selectById(obj.getOrderId());
        Validator.validateNotNull(mtOrder, "无此数据");
        mtOrder.setIsEvaluate(1);
        Validator.validateTrue(retBool(mtOrderMapper.updateById(mtOrder)), "增加商品评价失败");
        //先查询是否已经评价
        List<MtGoodsEvaluate> list = this.list(Wrappers.<MtGoodsEvaluate>lambdaQuery().eq(MtGoodsEvaluate::getUserId, SecurityUtils.getUser().getUserId()).eq(MtGoodsEvaluate::getOrderId, obj.getOrderId()));
        Validator.validateTrue(CollUtil.isEmpty(list), "该商品已经评价过无法再次评价!");
        //查询子订单
        List<MtOrderGoods> lsit = mtOrderGoodsMapper.selectList(Wrappers.<MtOrderGoods>lambdaQuery().eq(MtOrderGoods::getOrderId, obj.getOrderId()));
        lsit.forEach(e -> {
            MtGoodsEvaluate mtGoodsEvaluate = new MtGoodsEvaluate();
            BeanUtil.copyProperties(obj, mtGoodsEvaluate);
            mtGoodsEvaluate.setOrderId(mtOrder.getId());
            mtGoodsEvaluate.setShopId(mtOrder.getShopId());
            mtGoodsEvaluate.setOrderNo(mtOrder.getOrderNo());
            mtGoodsEvaluate.setOrderGoodsId(e.getId());
            mtGoodsEvaluate.setGoodsId(e.getGoodsId());
            if (CollUtil.isNotEmpty(obj.getImage())) {
                mtGoodsEvaluate.setImage(JSONUtil.toJsonStr(obj.getImage()));
            }
            mtGoodsEvaluate.setCreateTime(DateUtil.currentSeconds());
            mtGoodsEvaluate.setUserId(SecurityUtils.getUser().getUserId());
            mtGoodsEvaluate.setCreateBy(SecurityUtils.getUser().getUserId());
            Validator.validateTrue(this.save(mtGoodsEvaluate), "增加数据失败!");
            e.setIsEvaluate(1);
            Validator.validateTrue(retBool(mtOrderGoodsMapper.updateById(e)), "增加商品评价失败!");

            //增加商品数量
      /*      MtGoods mtGoods = mtGoodsMapper.selectById(e.getGoodsId());
            if (ObjectUtil.isNotNull(mtGoods)) {
                mtGoods.setSales(mtGoods.getSales() + e.getNum());
                Validator.validateTrue(retBool(mtGoodsMapper.updateById(mtGoods)), "增加商品评价失败!");
            }*/

        });
        //增加店铺星际
        MtShopping mtShopping = mtShoppingMapper.selectById(mtOrder.getShopId());
        if (ObjectUtil.isNotNull(mtShopping)) {
            //计算商品分数
            Integer scores = this.baseMapper.getScores(null, mtOrder.getShopId());
            Integer num = this.count(Wrappers.<MtGoodsEvaluate>lambdaQuery().eq(MtGoodsEvaluate::getShopId, mtOrder.getShopId()));
            mtShopping.setStars(BigDecimal.valueOf(scores).divide(BigDecimal.valueOf(num), 0, BigDecimal.ROUND_HALF_UP).intValue());
         //   mtShopping.setSales(mtShopping.getSales() + mtOrder.getNum());
            Validator.validateTrue(retBool(mtShoppingMapper.updateById(mtShopping)), "增加商品评价失败!");
        }
        return Boolean.TRUE;

    }

    /**
     * @Description: 修改我的商品评价
     * @Param: ApiGoodsEvaluateEditDto
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/29  0027
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean editObj(ApiGoodsEvaluateEditDto obj) {
        MtGoodsEvaluate mtGoodsEvaluate = this.getById(obj.getId());
        Validator.validateNotNull(mtGoodsEvaluate, "无此数据");
        MtOrder mtOrder = mtOrderMapper.selectById(obj.getOrderId());
        Validator.validateNotNull(mtOrder, "无此数据");
        BeanUtil.copyProperties(obj, mtGoodsEvaluate);
        if (CollUtil.isNotEmpty(obj.getImage())) {
            mtGoodsEvaluate.setImage(JSONUtil.toJsonStr(obj.getImage()));
        }
        mtGoodsEvaluate.setCreateTime(DateUtil.currentSeconds());
        mtGoodsEvaluate.setUserId(SecurityUtils.getUser().getUserId());
        mtGoodsEvaluate.setCreateBy(SecurityUtils.getUser().getUserId());
        Validator.validateTrue(this.updateById(mtGoodsEvaluate), "增加数据失败!");
        return Boolean.TRUE;
    }

    /**
     * @Description: 删除我的商品评价
     * @Param: ids
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/29  0027
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteObj(Long id) {
        MtGoodsEvaluate dogNews = this.getById(id);
        Validator.validateNotNull(dogNews, "无此数据!");
        Validator.validateTrue(this.removeById(id), "数据删除失败!");
        return Boolean.TRUE;

    }

    /**
     * @Description: 删除商品评价
     * @Param: ids
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/29  0027
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteObjs(List<Long> id) {
        // 判断是否为空
        Validator.validateTrue(CollUtil.isNotEmpty(id), "主键标识为空");
        Validator.validateTrue(this.removeByIds(id), "数据删除失败!");
        return Boolean.TRUE;

    }
}
